package com.rzjm.exercise.sys.system.user.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.constant.Constant;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.common.utils.WxMessage;
import com.rzjm.exercise.common.utils.encryp.impl.MD5Utils;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.system.dept.domain.DeptDO;
import com.rzjm.exercise.sys.system.role.domain.RoleDO;
import com.rzjm.exercise.sys.system.role.service.RoleService;
import com.rzjm.exercise.sys.system.user.domain.SysUserTownRelation;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.SysUserTownRelationService;
import com.rzjm.exercise.sys.system.user.service.UserService;
import com.rzjm.exercise.sys.vo.Tree;
import com.rzjm.exercise.sys.vo.UserVO;
import com.vdurmont.emoji.EmojiParser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("sys/user")
@Controller
public class UserController extends BaseController {
    private String prefix = "system/user";
    @Resource
    UserService userService;
    @Resource
    UserMpService userMpService;
    @Resource
    WxUserService wxUserService;
    @Resource
    RoleService roleService;
    @Resource
    DictService dictService;
    @Resource
    private ShopService shopService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private SysUserTownRelationService sysUserTownRelationService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private TownsService townsService;
    @Resource
    private DepartmentService departmentService;

    @Value("${wechat.appid_mp}")
    private String appidMp;//图片地址
    @Value("${wechat.secret_mp}")
    private String secretMp;//图片地址


    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        QueryWrapper<Towns> qwTown = new QueryWrapper<>();
        qwTown.eq("parent_id", 0);
        qwTown.eq("district_id", 1319);
        List<Towns> townsList = townsService.list(qwTown);
        model.addAttribute("townsList", townsList);
        model.addAttribute("userType", 1);
        return prefix + "/user";
    }

    @RequiresPermissions("sys:user:jituan:user")
    @GetMapping("/jituan")
    String jituan(Model model) {
        model.addAttribute("userType", 2);
        return prefix + "/jituan_user";
    }

    @RequiresPermissions("sys:user:jituanzongjian:user")
    @GetMapping("/jituanzongjian")
    String jituanzongjian(Model model) {
        model.addAttribute("userType", 2);
        return prefix + "/jituanzongjian/index";
    }

    @RequiresPermissions("sys:user:pianqu:user")
    @GetMapping("/pianqu")
    String pianqu(Model model) {
        model.addAttribute("userType", 3);
        return prefix + "/pianqu_user";
    }

    @RequiresPermissions("sys:user:pianqu:user")
    @GetMapping("/peifangshi")
    String peifangshi(Model model) {
        model.addAttribute("userType", 3);
        return prefix + "/peifangshi/peifangshi";
    }

    @RequiresPermissions("sys:user:fenchang:user")
    @GetMapping("/fenchang")
    String fenchangUser(Model model) {
        UserDO userDO = getUser();
        model.addAttribute("userType", 4);
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 1);
        queryWrapper.ne("shop_type", 3);
        if(userDO.getUserType() == 10){
            if (userDO.getTownId() != null && userDO.getTownId() > 0) {
                queryWrapper.eq("town_id", userDO.getTownId());
            }
        }else if(userDO.getUserType() == 2){
            queryWrapper.eq("group_id", userDO.getGroupId());
        }else if(userDO.getUserType() == 3){
            queryWrapper.eq("pianqu_id", userDO.getPianquId());
        }
        List<Shop> shopList = shopService.list(queryWrapper);
        model.addAttribute("shopList", shopList);

        return prefix + "/fenchang_user";
    }

    @RequiresPermissions("sys:user:checkuser:user")
    @GetMapping("/checkuser")
    String checkUser(Model model) {
        model.addAttribute("userType", 5);
        model.addAttribute("isBack", 0);
        return prefix + "/check_user";
    }

    @RequiresPermissions("sys:user:checkuser:user")
    @GetMapping("/checkuser/{shopId}")
    String checkUserShop(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("userType", 5);
        model.addAttribute("shopId", shopId);
        model.addAttribute("isBack", 1);
        return prefix + "/check_user";
    }

    @RequiresPermissions("sys:user:repair:user")
    @GetMapping("/repair")
    String repairUser(Model model) {
        model.addAttribute("userType", 6);
        model.addAttribute("isBack", 0);
        return prefix + "/repair_user";
    }

    @RequiresPermissions("sys:user:repair:user")
    @GetMapping("/repairUser/{shopId}")
    String repairUserShop(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("userType", 6);
        model.addAttribute("shopId", shopId);
        model.addAttribute("isBack", 1);
        return prefix + "/repair_user";
    }

    @RequiresPermissions("sys:baobaouser:baobaouser")
    @GetMapping("/baobao")
    String baobao(Model model) {
        model.addAttribute("userType", 7);
        UserDO user = getUser();
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("state", 1);
        qw.eq("parent_id", 0);
        if (user.getUserLevel() != null && user.getUserType() == 7) {
            if (user.getUserLevel() == 2 || user.getUserLevel() == 3) {//镇
                qw.eq("id", user.getTownId());
            }
        }

        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = new ArrayList<>();
        if (user.getUserLevel() != null && user.getUserLevel() == 3) {
            villages = townsService.selectListByColumn("parent_id", user.getVillageId());
        } else {
            villages = townsService.selectListByColumn("parent_id", towns.get(0).getId());
        }
        model.addAttribute("towns", towns);
        model.addAttribute("villages", villages);

        return prefix + "/baobao_user";
    }


    /**
     * 包保人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/baobao_list")
    @ResponseBody
    DataTableLayUI<UserDO> baobaoList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();

        Map<String, Object> map1 = new HashMap<>();
        String keyword = map.containsKey("search_like_keyword") ? map.get("search_like_keyword").toString() : null;
        String townId = map.containsKey("search_eq_townId") ? map.get("search_eq_townId").toString() : null;
        String villageId = map.containsKey("search_eq_villageId") ? map.get("search_eq_villageId").toString() : null;
        String checkType = map.containsKey("checkType") ? map.get("checkType").toString() : null;
        String userLevel = map.containsKey("userLevel") ? map.get("userLevel").toString() : null;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 7);
        map1.put("user_type", 7);

        UserDO user = getUser();
        if (user.getUserType() != null && user.getUserType() == 7) {
            if (user.getUserLevel() == 2) {//镇
                map1.put("town_id", user.getTownId());

                if (StrUtil.isNotEmpty(villageId)) {
                    map1.put("village_id", villageId);
                }
            } else if (user.getUserLevel() == 3) {//村
                map1.put("village_id", user.getVillageId());
            }
        } else {
            if (StrUtil.isNotEmpty(townId)) {
                map1.put("town_id", townId);
            }
            if (StrUtil.isNotEmpty(villageId)) {
                map1.put("village_id", villageId);
            }
        }

        if (StrUtil.isNotEmpty(keyword)) {
            map1.put("keyword", keyword);
        }

        if (StrUtil.isNotEmpty(checkType)) {
            map1.put("check_type", checkType);
        }

        if (StrUtil.isNotEmpty(userLevel)) {
            map1.put("user_level", userLevel);
        }

        Page<UserDO> page = userService.getPage(condition);
        List<UserDO> list = userService.getBaoBaoListByUserId(page, map1);
        list.forEach(user1 -> {
//			RoleDO roleDO = roleService.findById(user1.getRoleId());
//			if(roleDO!=null){
//				user1.setRoleName(roleDO.getRoleName());
//			}
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        DataTableLayUI<UserDO> dt = userService.pageSearchCustom(page, list, condition);
        return dt;
    }

    @GetMapping("/list")
    @ResponseBody
    DataTableLayUI<UserDO> list(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        Integer[] userTypes = { 0 ,1 ,2, 12,10,11};
        qw.in("user_type", Arrays.asList(userTypes));
        if(StrUtil.isNotEmpty(keyword)){
            qw.and(wrapper->{
                wrapper.like("name",keyword).or().like("username",keyword).or().like("mobile",keyword);
            });
        }
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            RoleDO roleDO = roleService.findById(user1.getRoleId());
            if(roleDO != null){
                user1.setRoleName(roleDO.getRoleName());
            }
        });
        return dt;
    }

    /**
     * 企业列表里的 巡检人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/jituan_list")
    @ResponseBody
    DataTableLayUI<UserDO> jituanList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 2);
        qw.ne("role_id", 18);
        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        return dt;
    }
    /**
     * 企业列表里的 j集团总监
     *
     * @param condition
     * @return
     */
    @GetMapping("/jituanzongjian_list")
    @ResponseBody
    DataTableLayUI<UserDO> jituanzongjianList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 2);
        qw.eq("role_id", 18);
        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        return dt;
    }
    /**
     * 企业列表里的 巡检人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/pianqu_list")
    @ResponseBody
    DataTableLayUI<UserDO> pianquList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        UserDO user = getUser();
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 3);
        qw.ne("role_id", 17);
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        }

        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            Pianqus pianqus = pianqusService.getById(user1.getPianquId());
            if (pianqus != null) {
                user1.setPianquName(pianqus.getPianquName());
            }

            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        return dt;
    }

    /**
     * 企业列表里的 巡检人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/peifangshi_list")
    @ResponseBody
    DataTableLayUI<UserDO> peifangshiList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        UserDO user = getUser();
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 3);
        qw.eq("role_id", 17);
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        }

        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            Pianqus pianqus = pianqusService.getById(user1.getPianquId());
            if (pianqus != null) {
                user1.setPianquName(pianqus.getPianquName());
            }

            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        return dt;
    }

    /**
     * 企业列表里的 分厂管理员人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/fenchang_list")
    @ResponseBody
    DataTableLayUI<UserDO> fenchangList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        int shopId = map.containsKey("search_eq_shopId") && StrUtil.isNotEmpty(map.get("search_eq_shopId").toString()) ? Integer.parseInt(map.get("search_eq_shopId").toString()) : 0;
        UserDO user = getUser();
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", 4);
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        } else if (user.getUserType() == 3) {
            qw.eq("pianqu_id", user.getPianquId());
        }

        if(shopId > 0){
            qw.eq("shop_id", shopId);
        }


        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        list.forEach(user1 -> {
            Shop shop = shopService.findById(user1.getShopId());
            if (shop != null) {
                user1.setShopName(shop.getShopName());
            }

            user1.setIsGuanZhuMp("未关注");
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                String guanzhu = "";
                for (WxUser wxUser : users) {
                    String nick_name = "";
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                        nick_name = EmojiParser.parseToUnicode(wxUser.getNickName());
                    }
                    UserMp userMp = userMpService.selectByUniqueColumn("unionid", wxUser.getUnionId());
                    if (userMp != null) {
                        guanzhu += nick_name + " : 已关注、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                } else {
                    name = "未绑定微信用户";
                }
                if (!guanzhu.equals("")) {
                    guanzhu = guanzhu.substring(0, guanzhu.length() - 1);
                } else {
                    guanzhu = "未关注";
                }
                user1.setWxNickName(name);
                user1.setIsGuanZhuMp(guanzhu);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        });
        return dt;
    }

    /**
     * 企业列表里的 巡检人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/check_list")
    @ResponseBody
    DataTableLayUI<UserDO> checkList(DataTableLayUI<UserDO> condition) {
        UserDO user = getUser();
        Map<String, Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString() : null;
        String userType = map.containsKey("search_eq_userType") ? map.get("search_eq_userType").toString() : null;
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        Integer shop_id = 0;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        if (userType != null) {
            qw.eq("user_type", Integer.parseInt(userType));
        } else {
            qw.eq("user_type", 5);//默认5 巡检用户
        }
        if (StrUtil.isNotEmpty(shopId)) {
            shop_id = Integer.parseInt(shopId);
            qw.eq("shop_id", shop_id);
        }
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        } else if (user.getUserType() == 3) {
            qw.eq("pianqu_id", user.getPianquId());
        } else if (user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6) {
            qw.eq("shop_id", user.getShopId());
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        for (UserDO user1 : list) {
            Shop shop = shopService.findById(user1.getShopId());
            if (shop != null) {
                user1.setShopName(shop.getShopName());
            }
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                for (WxUser wxUser : users) {
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                }
                user1.setWxNickName(name);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        }
        return dt;
    }

    /**
     * 企业列表里的 巡检人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/repair_list")
    @ResponseBody
    DataTableLayUI<UserDO> repairList(DataTableLayUI<UserDO> condition) {
        UserDO user = getUser();
        Map<String, Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString() : null;
        String userType = map.containsKey("search_eq_userType") ? map.get("search_eq_userType").toString() : null;
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        Integer shop_id = 0;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        if (userType != null) {
            qw.eq("user_type", Integer.parseInt(userType));
        } else {
            qw.eq("user_type", 5);//默认5 巡检用户
        }
        if (StrUtil.isNotEmpty(shopId)) {
            shop_id = Integer.parseInt(shopId);
            qw.eq("shop_id", shop_id);
        }
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        } else if (user.getUserType() == 3) {
            qw.eq("pianqu_user_id", user.getUserId());
        } else if (user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6) {
            qw.eq("shop_id", user.getShopId());
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        for (UserDO user1 : list) {
            Shop shop = shopService.findById(user1.getShopId());
            if (shop != null) {
                user1.setShopName(shop.getShopName());
            }

            user1.setIsGuanZhuMp("未关注");
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                String guanzhu = "";
                for (WxUser wxUser : users) {
                    String nick_name = "";
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                        nick_name = EmojiParser.parseToUnicode(wxUser.getNickName());
                    }
                    UserMp userMp = userMpService.selectByUniqueColumn("unionid", wxUser.getUnionId());
                    if (userMp != null) {
                        guanzhu += nick_name + " : 已关注、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                } else {
                    name = "未绑定微信用户";
                }
                if (!guanzhu.equals("")) {
                    guanzhu = guanzhu.substring(0, guanzhu.length() - 1);
                } else {
                    guanzhu = "未关注";
                }
                user1.setWxNickName(name);
                user1.setIsGuanZhuMp(guanzhu);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        }
        return dt;
    }


    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        UserDO userDO = new UserDO();
        List<RoleDO> roles = roleService.list();
        model.addAttribute("roles", roles);
        model.addAttribute("user", userDO);
        return prefix + "/add";
    }

    @RequiresPermissions("sys:baobaouser:add")
    @Log("添加用户")
    @GetMapping("/addBaoBao")
    String addBaoBao(Model model) {

        UserDO user = getUser();
        UserDO userDO = new UserDO();
        userDO.setUserType(7);
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("state", 1);
        qw.eq("parent_id", 0);
        if (user.getUserType() == 7) {
            if (user.getUserLevel() == 2 || user.getUserLevel() == 3) {//镇
                qw.eq("id", user.getTownId());
            }
        }
        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = new ArrayList<>();
        if (user.getUserLevel() == 3) {
            villages = townsService.selectListByColumn("id", user.getVillageId());
        } else {
            villages = townsService.selectListByColumn("parent_id", towns.get(0).getId());
        }
        model.addAttribute("towns", towns);
        model.addAttribute("villages", villages);
        model.addAttribute("currentUser", user);

        List<RoleDO> roles = roleService.selectListByColumn("user_type", 7);
        model.addAttribute("roles", roles);

        model.addAttribute("user", userDO);
        return prefix + "/edit_baobao";
    }

    @RequiresPermissions("sys:baobaouser:edit")
    @Log("添加用户")
    @GetMapping("/editBaoBao/{id}")
    String editBaoBao(Model model, @PathVariable("id") Integer id) {
        UserDO user = getUser();
        UserDO userDO = userService.get(id);
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("state", 1);
        qw.eq("parent_id", 0);
        if (user.getUserType() == 7) {
            if (user.getUserLevel() == 2 || user.getUserLevel() == 3) {//镇
                qw.eq("id", user.getTownId());
            }
        }
        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = new ArrayList<>();
        if (user.getUserLevel() == 3) {
            villages = townsService.selectListByColumn("id", user.getVillageId());
        } else {
            if (userDO.getTownId() != null) {
                villages = townsService.selectListByColumn("parent_id", userDO.getTownId());
            } else {
                villages = townsService.selectListByColumn("parent_id", towns.get(0).getId());
            }
        }
        model.addAttribute("towns", towns);
        model.addAttribute("villages", villages);
        model.addAttribute("user", userDO);
        model.addAttribute("currentUser", user);
        List<RoleDO> roles = roleService.selectListByColumn("user_type", 7);
        model.addAttribute("roles", roles);
        return prefix + "/edit_baobao";
    }

    @RequiresPermissions(value = {"sys:user:checkuser:add", "sys:user:pianqu:add",
            "sys:user:fenchang:add", "sys:baobaouser:add", "sys:user:checkDanger:add"}, logical = Logical.OR)
    @Log("添加巡检用户")
    @GetMapping("/addCheck/{userType}")
    String addCheck(Model model, @PathVariable("userType") Integer userType) {
        UserDO userDO = new UserDO();
        userDO.setUserType(userType);

        model.addAttribute("add_user_type", userType);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        int first_pianqu_user_id = 0;
        userDO.setJituanId(0);
        userDO.setPianquId(0);
        userDO.setFenchangId(0);

        QueryWrapper<Groups> qw = new QueryWrapper<>();
        qw.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qw);
        model.addAttribute("groups", groups);

        UserDO local = getUser();
        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {//隐患用户
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", 10);
            if (local.getRoleId() != 13) {
                wrapper.ne("role_id", 13);
            }
            //企业管理员只能添加企业职工
            if (local.getRoleId() == 11) {
                wrapper.eq("role_id", 12);
            }
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userLocal.getTownId() != null && userLocal.getTownId() > 0) {
                queryWrapper.eq("town_id", userLocal.getTownId());
            }
            if(userLocal.getUserType() == 2){
                queryWrapper.eq("group_id", userLocal.getGroupId());
            }else if(userLocal.getUserType() == 3){
                queryWrapper.eq("pianqu_id", userLocal.getPianquId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            if (userLocal.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userLocal.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
            model.addAttribute("shopList", shopList);
        } else if (local.getUserType() >= 3) {//片区管理人员 只能看到当前自己片区的
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", local.getPianquId());
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (local.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", local.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);

            model.addAttribute("pianqus", pianqus);

            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", userType);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
        } else {
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.ne("user_type", 0);
            wrapper.ne("user_type", 1);
            wrapper.ne("role_id", 13);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);

            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw_jituan = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是片区  只显示当前片区的
        } else {
            if (userLocal.getUserType() != 0) {
                qw_jituan.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
            }
        }
        qw_jituan.last("limit 1");
//		qw_jituan.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw_jituan);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        List<UserDO> users = new ArrayList<>();
        QueryWrapper<UserDO> qw_users = new QueryWrapper<>();
        qw_users.eq("user_type", 3);//片区管理员
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            if (pianqus != null && pianqus.size() > 0) {
                qw_users.eq("jituan_id", userLocal.getUserId());
                qw_users.eq("pianqu_id", pianqus.get(0).getId());
                users = userService.list(qw_users);
            }
        } else if (userLocal.getUserType() == 3) {
            qw_users.eq("pianqu_id", jituan_users.get(0).getPianquId());
            users = userService.list(qw_users);
        } else {
            if (userLocal.getUserType() != 0) {
//				qw_users.eq("jituan_id", userLocal.getJituanId());
                qw_users.eq("pianqu_id", userLocal.getPianquId());
            }
            users = userService.list(qw_users);
        }
        if (users != null && users.size() > 0) {
            first_pianqu_user_id = users.get(0).getUserId();
        }
        model.addAttribute("users", users);

        if (userType == 3) {//添加的是片区账号
            userDO.setJituanId(userLocal.getUserId());
        } else if (userType == 4) {//添加的是 分厂管理员
            //查询所有跟自己绑定的企业
            Map<String, Object> map = new HashMap<>();
            userDO.setJituanId(userLocal.getJituanId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                //集团管理员无需默认分区
                userDO.setJituanId(userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
            } else if (userLocal.getUserType() == 3) {
                userDO.setPianquId(userLocal.getUserId());//当前登录的是分区管理员 可默认分区管理员的 片区
                model.addAttribute("pianquUserId", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
            }

//            if (userLocal.getUserType() != 0) {
//                map.put("sys_user_id", first_pianqu_user_id);
//            }
            List<Shop> list0 = shopService.getPageByUserId(map);
            model.addAttribute("shops", list0);
        } else {//添加的是巡检员
            userDO.setJituanId(userLocal.getJituanId());
            userDO.setPianquUserId(userLocal.getPianquUserId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                userDO.setJituanId(userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("jituan_user_id", userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);

            } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
                userDO.setPianquId(userLocal.getUserId());
                model.addAttribute("pianquUserId", userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("sys_user_id", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);
                model.addAttribute("pianquUserId", userLocal.getUserId());
            } else if (userLocal.getUserType() == 4 || userLocal.getUserType() == 5 || userLocal.getUserType() == 6) {
                model.addAttribute("shop_id", userLocal.getShopId());
            }
            if (userLocal.getUserType() == 4) {
                userDO.setFenchangId(userLocal.getFenchangId());
            }
            model.addAttribute("role_id", userLocal.getRoleId());
        }
        model.addAttribute("user", userDO);
        return prefix + "/add_check";
    }

    @GetMapping("/addPeifangshi")
    String addPeifangshi(Model model) {
        Integer userType = 3;
        UserDO userDO = new UserDO();
        userDO.setUserType(userType);
        List<DictDO> dictDOS = dictService.selectListByColumn("type","pianqu-job");
        model.addAttribute("dicts",dictDOS);
        model.addAttribute("add_user_type", userType);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        int first_pianqu_user_id = 0;
        userDO.setJituanId(0);
        userDO.setPianquId(0);
        userDO.setFenchangId(0);

        QueryWrapper<Groups> qw = new QueryWrapper<>();
        qw.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qw);
        model.addAttribute("groups", groups);

        UserDO local = getUser();
        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {//隐患用户
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", 10);
            if (local.getRoleId() != 13) {
                wrapper.ne("role_id", 13);
            }
            //企业管理员只能添加企业职工
            if (local.getRoleId() == 11) {
                wrapper.eq("role_id", 12);
            }
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userLocal.getTownId() != null && userLocal.getTownId() > 0) {
                queryWrapper.eq("town_id", userLocal.getTownId());
            }
            if(userLocal.getUserType() == 2){
                queryWrapper.eq("group_id", userLocal.getGroupId());
            }else if(userLocal.getUserType() == 3){
                queryWrapper.eq("pianqu_id", userLocal.getPianquId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            if (userLocal.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userLocal.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
            model.addAttribute("shopList", shopList);
        } else if (local.getUserType() >= 3) {//片区管理人员 只能看到当前自己片区的
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", local.getPianquId());
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (local.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", local.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);

            model.addAttribute("pianqus", pianqus);

            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", userType);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
        } else {
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.ne("user_type", 0);
            wrapper.ne("user_type", 1);
            wrapper.ne("role_id", 13);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);

            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw_jituan = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是片区  只显示当前片区的
        } else {
            if (userLocal.getUserType() != 0) {
                qw_jituan.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
            }
        }
        qw_jituan.last("limit 1");
//		qw_jituan.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw_jituan);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        List<UserDO> users = new ArrayList<>();
        QueryWrapper<UserDO> qw_users = new QueryWrapper<>();
        qw_users.eq("user_type", 3);//片区管理员
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            if (pianqus != null && pianqus.size() > 0) {
                qw_users.eq("jituan_id", userLocal.getUserId());
                qw_users.eq("pianqu_id", pianqus.get(0).getId());
                users = userService.list(qw_users);
            }
        } else if (userLocal.getUserType() == 3) {
            qw_users.eq("pianqu_id", jituan_users.get(0).getPianquId());
            users = userService.list(qw_users);
        } else {
            if (userLocal.getUserType() != 0) {
//				qw_users.eq("jituan_id", userLocal.getJituanId());
                qw_users.eq("pianqu_id", userLocal.getPianquId());
            }
            users = userService.list(qw_users);
        }
        if (users != null && users.size() > 0) {
            first_pianqu_user_id = users.get(0).getUserId();
        }
        model.addAttribute("users", users);

        if (userType == 3) {//添加的是片区账号
            userDO.setJituanId(userLocal.getUserId());
        } else if (userType == 4) {//添加的是 分厂管理员
            //查询所有跟自己绑定的企业
            Map<String, Object> map = new HashMap<>();
            userDO.setJituanId(userLocal.getJituanId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                //集团管理员无需默认分区
                userDO.setJituanId(userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
            } else if (userLocal.getUserType() == 3) {
                userDO.setPianquId(userLocal.getUserId());//当前登录的是分区管理员 可默认分区管理员的 片区
                model.addAttribute("pianquUserId", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
            }

//            if (userLocal.getUserType() != 0) {
//                map.put("sys_user_id", first_pianqu_user_id);
//            }
            List<Shop> list0 = shopService.getPageByUserId(map);
            model.addAttribute("shops", list0);
        } else {//添加的是巡检员
            userDO.setJituanId(userLocal.getJituanId());
            userDO.setPianquUserId(userLocal.getPianquUserId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                userDO.setJituanId(userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("jituan_user_id", userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);

            } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
                userDO.setPianquId(userLocal.getUserId());
                model.addAttribute("pianquUserId", userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("sys_user_id", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);
                model.addAttribute("pianquUserId", userLocal.getUserId());
            } else if (userLocal.getUserType() == 4 || userLocal.getUserType() == 5 || userLocal.getUserType() == 6) {
                model.addAttribute("shop_id", userLocal.getShopId());
            }
            if (userLocal.getUserType() == 4) {
                userDO.setFenchangId(userLocal.getFenchangId());
            }
            model.addAttribute("role_id", userLocal.getRoleId());
        }
        model.addAttribute("user", userDO);
        return prefix + "/peifangshi/add_peifangshi";
    }

    @GetMapping("/addJituanzongjian")
    String addJituanzongjian(Model model) {
        Integer userType = 2;
        UserDO userDO = new UserDO();
        userDO.setUserType(userType);
        List<DictDO> dictDOS = dictService.selectListByColumn("type","jituan-job");
        model.addAttribute("dicts",dictDOS);
        model.addAttribute("add_user_type", userType);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        int first_pianqu_user_id = 0;
        userDO.setJituanId(0);
        userDO.setPianquId(0);
        userDO.setFenchangId(0);

        QueryWrapper<Groups> qw = new QueryWrapper<>();
        qw.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qw);
        model.addAttribute("groups", groups);

        UserDO local = getUser();
        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {//隐患用户
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", 10);
            if (local.getRoleId() != 13) {
                wrapper.ne("role_id", 13);
            }
            //企业管理员只能添加企业职工
            if (local.getRoleId() == 11) {
                wrapper.eq("role_id", 12);
            }
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userLocal.getTownId() != null && userLocal.getTownId() > 0) {
                queryWrapper.eq("town_id", userLocal.getTownId());
            }
            if(userLocal.getUserType() == 2){
                queryWrapper.eq("group_id", userLocal.getGroupId());
            }else if(userLocal.getUserType() == 3){
                queryWrapper.eq("pianqu_id", userLocal.getPianquId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            if (userLocal.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userLocal.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
            model.addAttribute("shopList", shopList);
        } else if (local.getUserType() >= 3) {//片区管理人员 只能看到当前自己片区的
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", local.getPianquId());
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (local.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", local.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);

            model.addAttribute("pianqus", pianqus);

            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", userType);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
        } else {
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.ne("user_type", 0);
            wrapper.ne("user_type", 1);
            wrapper.ne("role_id", 13);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);

            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw_jituan = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是片区  只显示当前片区的
        } else {
            if (userLocal.getUserType() != 0) {
                qw_jituan.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
            }
        }
        qw_jituan.last("limit 1");
//		qw_jituan.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw_jituan);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        List<UserDO> users = new ArrayList<>();
        QueryWrapper<UserDO> qw_users = new QueryWrapper<>();
        qw_users.eq("user_type", 3);//片区管理员
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            if (pianqus != null && pianqus.size() > 0) {
                qw_users.eq("jituan_id", userLocal.getUserId());
                qw_users.eq("pianqu_id", pianqus.get(0).getId());
                users = userService.list(qw_users);
            }
        } else if (userLocal.getUserType() == 3) {
            qw_users.eq("pianqu_id", jituan_users.get(0).getPianquId());
            users = userService.list(qw_users);
        } else {
            if (userLocal.getUserType() != 0) {
//				qw_users.eq("jituan_id", userLocal.getJituanId());
                qw_users.eq("pianqu_id", userLocal.getPianquId());
            }
            users = userService.list(qw_users);
        }
        if (users != null && users.size() > 0) {
            first_pianqu_user_id = users.get(0).getUserId();
        }
        model.addAttribute("users", users);

        if (userType == 3) {//添加的是片区账号
            userDO.setJituanId(userLocal.getUserId());
        } else if (userType == 4) {//添加的是 分厂管理员
            //查询所有跟自己绑定的企业
            Map<String, Object> map = new HashMap<>();
            userDO.setJituanId(userLocal.getJituanId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                //集团管理员无需默认分区
                userDO.setJituanId(userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
            } else if (userLocal.getUserType() == 3) {
                userDO.setPianquId(userLocal.getUserId());//当前登录的是分区管理员 可默认分区管理员的 片区
                model.addAttribute("pianquUserId", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
            }

//            if (userLocal.getUserType() != 0) {
//                map.put("sys_user_id", first_pianqu_user_id);
//            }
            List<Shop> list0 = shopService.getPageByUserId(map);
            model.addAttribute("shops", list0);
        } else {//添加的是巡检员
            userDO.setJituanId(userLocal.getJituanId());
            userDO.setPianquUserId(userLocal.getPianquUserId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                userDO.setJituanId(userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("jituan_user_id", userLocal.getUserId());
                map.put("group_id", userLocal.getGroupId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);

            } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
                userDO.setPianquId(userLocal.getUserId());
                model.addAttribute("pianquUserId", userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
//                map.put("sys_user_id", userLocal.getUserId());
                map.put("pianqu_id", userLocal.getPianquId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);
                model.addAttribute("pianquUserId", userLocal.getUserId());
            } else if (userLocal.getUserType() == 4 || userLocal.getUserType() == 5 || userLocal.getUserType() == 6) {
                model.addAttribute("shop_id", userLocal.getShopId());
            }
            if (userLocal.getUserType() == 4) {
                userDO.setFenchangId(userLocal.getFenchangId());
            }
            model.addAttribute("role_id", userLocal.getRoleId());
        }
        model.addAttribute("user", userDO);
        return prefix + "/peifangshi/add_peifangshi";
    }

    @RequiresPermissions(value = {"sys:user:checkuser:add", "sys:user:pianqu:add", "sys:user:fenchang:add", "sys:baobaouser:add", "sys:user:checkDanger:add"}, logical = Logical.OR)
    @Log("添加巡检用户")
    @GetMapping("/addCheck/{userType}/{shopId}")
    String addCheckCompany(Model model, @PathVariable("userType") Integer userType, @PathVariable("shopId") Integer shopId) {
        UserDO userDO = new UserDO();
        userDO.setUserType(userType);
        model.addAttribute("add_user_type", userType);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        model.addAttribute("local_user_type", userLocal.getUserType());
        int first_pianqu_user_id = 0;
        userDO.setJituanId(0);
        userDO.setPianquId(0);
        userDO.setFenchangId(0);
        userDO.setShopId(shopId);

        QueryWrapper<Groups> qw = new QueryWrapper<>();
        qw.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qw);
        model.addAttribute("groups", groups);


        UserDO local = getUser();
        QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_type", 10);
        List<RoleDO> list = roleService.list(wrapper);
        model.addAttribute("roleList", list);

        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {//企业用户
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userLocal.getTownId() != null && userLocal.getTownId() > 0) {
                queryWrapper.eq("town_id", userLocal.getTownId());
            }
            if(userLocal.getUserType() == 2){
                queryWrapper.eq("group_id", userLocal.getGroupId());
            }else if(userLocal.getUserType() == 3){
                queryWrapper.eq("pianqu_id", userLocal.getPianquId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            model.addAttribute("shopList", shopList);
            if (userLocal.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userLocal.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
        } else if (local.getUserType() >= 3) {//片区管理人员 只能看到当前自己片区的
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", local.getPianquId());
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (local.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", local.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else {
            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        List<Department> departments = departmentService.selectListByColumn("company_id",shopId);
        model.addAttribute("deptList", departments);


        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw_jituan = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
            qw_jituan.eq("user_id", userLocal.getUserId());//如果当前是片区  只显示当前片区的
        } else {
            if (userLocal.getUserType() != 0) {
                qw_jituan.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
            }
        }
        qw_jituan.last("limit 1");
//		qw_jituan.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw_jituan);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        List<UserDO> users = new ArrayList<>();
        QueryWrapper<UserDO> qw_users = new QueryWrapper<>();
        qw_users.eq("user_type", 3);//片区管理员
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            if (pianqus != null && pianqus.size() > 0) {
                qw_users.eq("jituan_id", userLocal.getUserId());
                qw_users.eq("pianqu_id", pianqus.get(0).getId());
                users = userService.list(qw_users);
            }
        } else if (userLocal.getUserType() == 3) {
            qw_users.eq("pianqu_id", jituan_users.get(0).getPianquId());
            users = userService.list(qw_users);
        } else {
            if (userLocal.getUserType() != 0) {
//				qw_users.eq("jituan_id", userLocal.getJituanId());
                qw_users.eq("pianqu_id", userLocal.getPianquId());
            }
            users = userService.list(qw_users);
        }
        if (users != null && users.size() > 0) {
            first_pianqu_user_id = users.get(0).getUserId();
        }
        model.addAttribute("users", users);

        if (userType == 3) {//添加的是片区账号
            userDO.setJituanId(userLocal.getUserId());
        } else if (userType == 4) {//添加的是 分厂管理员
            userDO.setJituanId(userLocal.getJituanId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                //集团管理员无需默认分区
                userDO.setJituanId(userLocal.getUserId());
            } else if (userLocal.getUserType() == 3) {
                userDO.setPianquId(userLocal.getUserId());//当前登录的是分区管理员 可默认分区管理员的 片区
                model.addAttribute("pianquUserId", userLocal.getUserId());
            }
            //查询所有跟自己绑定的企业
            Map<String, Object> map = new HashMap<>();
            if (userLocal.getUserType() != 0) {
                map.put("sys_user_id", first_pianqu_user_id);
            }
            List<Shop> list0 = shopService.getPageByUserId(map);
            model.addAttribute("shops", list0);
        } else {//添加的是巡检员
            userDO.setJituanId(userLocal.getJituanId());
            userDO.setPianquUserId(userLocal.getPianquUserId());
            if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
                userDO.setJituanId(userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
                map.put("jituan_user_id", userLocal.getUserId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);

            } else if (userLocal.getUserType() == 3) {//当前登录的是 片区管理员
                userDO.setPianquId(userLocal.getUserId());
                model.addAttribute("pianquUserId", userLocal.getUserId());

                Map<String, Object> map = new HashMap<>();
                map.put("sys_user_id", userLocal.getUserId());
                List<Shop> list0 = shopService.getPageByUserId(map);
                model.addAttribute("shops", list0);
                model.addAttribute("pianquUserId", userLocal.getUserId());
            } else if (userLocal.getUserType() == 4 || userLocal.getUserType() == 5 || userLocal.getUserType() == 6) {
                model.addAttribute("shop_id", userLocal.getShopId());
            }
            if (userLocal.getUserType() == 4) {
                userDO.setFenchangId(userLocal.getFenchangId());
            }
            model.addAttribute("role_id", userLocal.getRoleId());
        }
        model.addAttribute("shop_id", shopId);
        model.addAttribute("user", userDO);
        return prefix + "/add_check_company";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Integer id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.selectAllList();
        model.addAttribute("roles", roles);
        List<Shop> list0 = shopService.selectAllList();
        model.addAttribute("shops", list0);
        return prefix + "/edit";
    }

    @RequiresPermissions(value = {"sys:user:checkuser:edit", "sys:user:pianqu:edit", "sys:user:fenchang:edit", "sys:baobaouser:edit", "sys:user:checkDanger:edit"}, logical = Logical.OR)
    @Log("编辑用户")
    @GetMapping("/editCheck/{id}")
    String editCheck(Model model, @PathVariable("id") Integer id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        int first_pianqu_user_id = 0;
        QueryWrapper<Groups> qwGroup = new QueryWrapper<>();
        qwGroup.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qwGroup);
        model.addAttribute("groups", groups);

        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            wrapper.eq("user_type", 10);
            if (userLocal.getRoleId() != 13) {
                wrapper.ne("role_id", 13);
            }
            //企业管理员只能添加企业职工
            if (userLocal.getRoleId() == 11) {
                wrapper.eq("role_id", 12);
            }
            List<RoleDO> list = roleService.list(wrapper);
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userDO.getTownId() != null && userDO.getTownId() > 0) {
                queryWrapper.eq("town_id", userDO.getTownId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            if (userDO.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userDO.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
            model.addAttribute("shopList", shopList);
            model.addAttribute("roleList", list);
        } else if (userLocal.getUserType() >= 3) {
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", userLocal.getPianquId());
            pianqus = pianqusService.selectListByQueryWrapper(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (userLocal.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", userLocal.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else {
            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3 || userLocal.getUserType() == 4) {
            qw.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
        }
        qw.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw1 = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw1.eq("jituan_id", userLocal.getUserId());
        } else if (userLocal.getUserType() == 3 || userLocal.getUserType() == 4) {
            qw1.eq("pianqu_id", userLocal.getPianquId());
        }
        qw1.eq("user_type", 3);//片区管理员
        List<UserDO> users = userService.list(qw1);
        if (users != null && users.size() > 0) {
            first_pianqu_user_id = users.get(0).getUserId();
        }
        model.addAttribute("users", users);

        Map<String, Object> map = new HashMap<>();
        if(userDO.getPianquUserId()!=null && userDO.getPianquUserId() > 0){
            map.put("sys_user_id", userDO.getPianquUserId());
        }else{
//            map.put("sys_user_id", first_pianqu_user_id);
        }
        if (userLocal.getUserType() == 2){
            map.put("group_id", userDO.getGroupId());
        }else if (userLocal.getUserType() == 3){
            map.put("pianqu_id", userDO.getPianquId());
        }else {
            map.put("id", userDO.getShopId());
        }
        List<Shop> list0 = shopService.getPageByUserId(map);
        model.addAttribute("shops", list0);


        if (userLocal.getUserType() < 2){
            QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
            Integer[] types = {3,4,5,6,10};
            wrapper.in("user_type", types);
            List<RoleDO> list = roleService.list(wrapper);
            model.addAttribute("roleList", list);
        }

        return prefix + "/edit_check_fenchang";
    }


    @RequiresPermissions(value = {"sys:user:checkuser:edit", "sys:user:pianqu:edit", "sys:user:fenchang:edit", "sys:baobaouser:edit", "sys:user:checkDanger:edit"}, logical = Logical.OR)
    @Log("编辑用户")
    @GetMapping("/editCheckCompany/{id}")
    String editCheckCompany(Model model, @PathVariable("id") Integer id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        UserDO userLocal = getUser();
        model.addAttribute("userLocal", userLocal);
        QueryWrapper<Groups> qwGroup = new QueryWrapper<>();
        qwGroup.gt("id", 1);
        List<Groups> groups = groupsService.selectListByQueryWrapper(qwGroup);
        model.addAttribute("groups", groups);


        QueryWrapper<RoleDO> wrapper = new QueryWrapper<>();
        Integer[] types = {4,5,6,10};
        if (userLocal.getUserType() < 2){
            types = new Integer[]{3,4,5,6,10};
        }
        wrapper.in("user_type", Arrays.asList(types));
        List<RoleDO> list = roleService.list(wrapper);
        model.addAttribute("roleList", list);

        List<Pianqus> pianqus = new ArrayList<>();
        if (userDO.getUserType() == 10) {
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("state", 1);
            queryWrapper.ne("shop_type", 3);
            if (userDO.getTownId() != null && userDO.getTownId() > 0) {
                queryWrapper.eq("town_id", userDO.getTownId());
            }
            List<Shop> shopList = shopService.list(queryWrapper);
            if (userDO.getShopId() != null) {
                List<Department> deptList = departmentService.selectListByColumn("company_id", userDO.getShopId());
                model.addAttribute("deptList", deptList);
            }
            QueryWrapper<Towns> qwTown = new QueryWrapper<>();
            qwTown.eq("parent_id", 0);
            qwTown.eq("district_id", 1319);
            List<Towns> townsList = townsService.list(qwTown);
            model.addAttribute("townsList", townsList);
            model.addAttribute("shopList", shopList);
        } else if (userLocal.getUserType() >= 3) {
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("id", userLocal.getPianquId());
            pianqus = pianqusService.selectListByQueryWrapper(qw1);
            model.addAttribute("pianqus", pianqus);
        } else if (userLocal.getUserType() == 2) {//集团用户
            QueryWrapper<Pianqus> qw1 = new QueryWrapper<>();
            qw1.eq("jituan_id", userLocal.getGroupId());//只看自己集团的
            pianqus = pianqusService.list(qw1);
            model.addAttribute("pianqus", pianqus);
        } else {
            pianqus = pianqusService.selectAllList();
            model.addAttribute("pianqus", pianqus);
        }

        List<Department> departments = departmentService.selectListByColumn("company_id",userDO.getShopId());
        model.addAttribute("deptList", departments);

        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw.eq("user_id", userLocal.getUserId());//如果当前是集团  只显示自己
        } else if (userLocal.getUserType() == 3 || userLocal.getUserType() == 4) {
            qw.eq("user_id", userLocal.getJituanId());//如果当前是集团  只显示自己
        }
        qw.eq("user_type", 2);//片区管理员
        List<UserDO> jituan_users = userService.list(qw);
        model.addAttribute("jituan_users", jituan_users);

        //查询所有跟自己绑定的企业
        QueryWrapper<UserDO> qw1 = new QueryWrapper<>();
        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            qw1.eq("jituan_id", userLocal.getUserId());
        } else if (userLocal.getUserType() == 3 || userLocal.getUserType() == 4) {
            qw1.eq("pianqu_id", userLocal.getPianquId());
        }
        qw1.eq("user_type", 3);//片区管理员
        List<UserDO> users = userService.list(qw1);
        model.addAttribute("users", users);

        List<Shop> list0 = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        if(userLocal.getGroupId() != null){
            map.put("group_id", userLocal.getGroupId());
        }
        if(userLocal.getPianquId()!= null){
            map.put("pianqu_id", userLocal.getPianquId());
        }

//        if(userLocal.getPianquUserId()!=null && userLocal.getPianquUserId() > 0){
//            map.put("sys_user_id", userLocal.getPianquUserId());
//            list0 = shopService.getPageByUserId(map);
//        }else{
//        }
        QueryWrapper<Shop> qwShop = new QueryWrapper<>();

        if (userLocal.getUserType() == 2) {//当前登录的是  集团管理员
            if(userLocal.getGroupId() != null){
                qwShop.eq("group_id",userLocal.getGroupId());
            }
        } else if (userLocal.getUserType() == 3) {
            if(userLocal.getPianquId() != null){
                qwShop.eq("pianqu_id",userLocal.getPianquId());
            }
        }else if(userLocal.getUserType() == 4 || userLocal.getUserType() == 5
                || userLocal.getUserType() == 6 || userLocal.getUserType() == 7 || userLocal.getUserType() == 10){
            qwShop.eq("id",userLocal.getShopId());
        }
        qwShop.eq("state",1);
        qwShop.ne("shop_type",3);

        list0 = shopService.list(qwShop);
        model.addAttribute("shops", list0);
        model.addAttribute("shopList", list0);


        return prefix + "/edit_check_company";
    }



    @RequiresPermissions("sys:user:band_shop")
    @Log("绑定企业")
    @GetMapping("/band_shop/{userId}")
    String bandShop(Model model, @PathVariable("userId") Integer userId) {
        UserDO userDO = userService.get(userId);
        model.addAttribute("user", userDO);

        List<Shop> list0 = shopService.selectAllList();
        model.addAttribute("shops", list0);

        return prefix + "/band_shop";
    }


    @RequiresPermissions(value = {"sys:user:add", "sys:user:jituan:add", "sys:user:checkuser:add", "sys:user:pianqu:add", "sys:user:fenchang:add", "sys:baobaouser:add", "sys:user:checkDanger:add"}, logical = Logical.OR)
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    R save(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        RoleDO role = roleService.findById(user.getRoleId());
        if (role != null) {
            user.setRoleId(role.getRoleId());
            user.setUserType(role.getUserType());
        } else {
            role = roleService.selectByUniqueColumn("user_type", user.getUserType());
            if (role != null) {
                user.setRoleId(role.getRoleId());
                user.setUserType(role.getUserType());
            }
        }
//        if (user.getShopId() == null) {
//            user.setShopId(0);
//        }
        if (user.getIsSendMsg() == null) {
            user.setIsSendMsg(0);
        }

        Pianqus pianqus = pianqusService.findById(user.getPianquId());
        UserDO local = getUser();
        if (local != null) {
            if (local.getUserType() == 10) {
                if (local.getTownId() != null && local.getTownId() > 0) {
                    user.setTownId(local.getTownId());
                }

                if (local.getShopId() != null && local.getShopId() > 0) {
                    user.setShopId(local.getShopId());
                }
            }else if (user.getUserType() > 3 && user.getUserType() < 10) {// 添加的是 集团以下的 角色，默认自己的所在集团
//				UserDO jituan = userService.findById(local.getJituanId());
//				if(jituan != null){
//				}
                if (local.getUserType() == 3) {
                    user.setPianquUserId(local.getUserId());
                }
                if (pianqus != null) {
                    user.setGroupId(pianqus.getJituanId());
                }
                if (local.getUserType() == 2) {
                    user.setJituanId(local.getUserId());//集团管理员id
                } else {
                    user.setJituanId(local.getJituanId());//集团管理员id
                }
            } else if (user.getUserType() == 3) {//如果添加的是片区管理员
                user.setGroupId(local.getGroupId());//集团 id
                if (local.getUserType() == 2) {
                    user.setJituanId(local.getUserId());//集团管理员id
                } else {
                    user.setJituanId(local.getJituanId());//集团管理员id
                }
            } else if (user.getUserType() == 2) {//如果添加的是集团角色
                user.setGroupId(user.getGroupId());
                user.setJituanId(0);
            } else {
                user.setGroupId(1);
                user.setJituanId(0);
            }
        }


        String villageName = user.getVillageName();
        if (StrUtil.isEmpty(villageName)) {
            Towns village = townsService.findById(user.getVillageId());
            if (village != null) {
                villageName = village.getTownName();
            }
        }

        String townName = user.getTownName();
        if (StrUtil.isEmpty(townName)) {
            Towns town = townsService.findById(user.getTownId());
            if (town != null) {
                townName = town.getTownName();
            }
        }
        user.setVillageName(villageName);
        user.setTownName(townName);


        if(pianqus != null){
            user.setGroupId(pianqus.getJituanId());
        }

        user.setStatus(1);
        if (StrUtil.isEmpty(user.getPassword())) {
            user.setPassword("123456");
        }
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));

        if (user.getTownId() == null) {
            user.setTownId(0);
        }

        if (userService.save(user)) {

            if (user.getUserType() == 7) {
                SysUserTownRelation relation = new SysUserTownRelation();
                relation.setSysUserId(user.getUserId());
                relation.setName(user.getName());
                relation.setTownId(user.getTownId());
                relation.setTownName(townName);
                relation.setVillageId(user.getVillageId());
                relation.setVillageName(villageName);
                relation.setCreateTime(new Date());
                relation.setState(1);
                if (role != null) {
                    if (role.getRoleId() == 8) {
                        relation.setCheckType(0);
                    } else if (role.getRoleId() == 9) {
                        relation.setCheckType(1);
                    }
                }
                sysUserTownRelationService.save(relation);
            }
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions(value = {"sys:user:edit", "sys:user:jituan:edit", "sys:user:checkuser:edit", "sys:user:pianqu:edit", "sys:user:fenchang:edit", "sys:baobaouser:edit", "sys:user:checkDanger:edit"}, logical = Logical.OR)
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    R update(UserDO user) {
        String villageName = user.getVillageName();
        if (StrUtil.isEmpty(villageName)) {
            Towns village = townsService.findById(user.getVillageId());
            if (village != null) {
                villageName = village.getTownName();
            }
        }

        String townName = user.getTownName();
        if (StrUtil.isEmpty(townName)) {
            Towns town = townsService.findById(user.getTownId());
            if (town != null) {
                townName = town.getTownName();
            }
        }
        user.setVillageName(villageName);
        user.setTownName(townName);

        RoleDO roleDO = roleService.findById(user.getRoleId());
        if(roleDO != null){
            user.setUserType(roleDO.getUserType());
        }

        UserDO localUser = getUser();
        if (user.getUserType() != null && user.getUserType() == 7) {
            List<SysUserTownRelation> relations = sysUserTownRelationService.selectListByColumn("sys_user_id", user.getUserId());
            for (SysUserTownRelation relation : relations) {
                relation.setTownId(user.getTownId());
                relation.setTownName(townName);
                relation.setVillageId(user.getVillageId());
                relation.setVillageName(villageName);
                sysUserTownRelationService.updateById(relation);
            }
        }

        Pianqus pianqus = pianqusService.findById(user.getPianquId());
        UserDO local = getUser();
        if (local != null) {
            if (local.getUserType() == 10) {
                if (local.getTownId() != null && local.getTownId() > 0) {
                    user.setTownId(local.getTownId());
                }

                if (local.getShopId() != null && local.getShopId() > 0) {
                    user.setShopId(local.getShopId());
                }
            }else if (user.getUserType() > 3 && user.getUserType() < 10) {// 添加的是 集团以下的 角色，默认自己的所在集团
                if (local.getUserType() == 3) {
                    user.setPianquUserId(local.getUserId());
                }
                if (pianqus != null) {
                    user.setGroupId(pianqus.getJituanId());
                }
                if (local.getUserType() == 2) {
                    user.setJituanId(local.getUserId());//集团管理员id
                } else {
                    user.setJituanId(local.getJituanId());//集团管理员id
                }
            } else if (user.getUserType() == 3) {//如果添加的是片区管理员
                user.setGroupId(local.getGroupId());//集团 id
                if (local.getUserType() == 2) {
                    user.setJituanId(local.getUserId());//集团管理员id
                } else {
                    user.setJituanId(local.getJituanId());//集团管理员id
                }
            } else if (user.getUserType() == 2) {//如果添加的是集团角色
                user.setGroupId(user.getGroupId());
                user.setJituanId(0);
            } else {
                user.setGroupId(1);
                user.setJituanId(0);
            }
        }

        if (user.getShopId() == null) {
            user.setShopId(0);
        }else {
            Shop shop = shopService.findById(user.getShopId());
            user.setGroupId(shop.getGroupId());
            user.setPianquId(shop.getPianquId());
        }
        if (user.getTownId() == null) {
            user.setTownId(0);
        }
        if (userService.update(user) > 0) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions(value = {"sys:user:fenchang:edit"}, logical = Logical.OR)
    @Log("更新用户")
    @PostMapping("/updateSendMsg")
    @ResponseBody
    R updateSendMsg(UserDO user) {
        if (userService.update(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePersonal")
    @ResponseBody
    R updatePersonal(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }

        if (userService.updatePersonal(user) > 0) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    R remove(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }


    @Log("删除用户")
    @RequiresPermissions(value = {"sys:user:checkuser:remove"})
    @PostMapping("/remove/checkuser")
    @ResponseBody
    R removecheckUser(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions(value = {"sys:user:fenchang:remove"})
    @Log("删除用户")
    @PostMapping("/remove/fenchang")
    @ResponseBody
    R removefenchang(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions(value = {"sys:baobaouser:remove"})
    @Log("删除用户")
    @PostMapping("/remove/baobao")
    @ResponseBody
    R removeBaobao(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:pianqu:remove")
    @Log("删除用户")
    @PostMapping("/remove/pianqu")
    @ResponseBody
    R removepianqu(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:checkDanger:remove")
    @Log("删除用户")
    @PostMapping("/remove/checkDanger")
    @ResponseBody
    R removecheckDanger(Long id) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Integer[] userIds) {
//		if (Constant.SUPER_ACCOUNT.equals(getUsername())) {
//			return R.error(1, "超级管理员账号不能删除");
//		}
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.removeByIds(Arrays.asList(userIds))) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Integer userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    R resetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        UserDO userDO = userService.get(userVO.getUserId());
        userVO.setUserDO(userDO);
        try {
            userService.resetPwd(userVO, getUser());
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    R adminResetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.adminResetPwd(userVO);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(1, e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        model.addAttribute("user", userDO);
        return prefix + "/edit_personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        Map<String, Object> result = new HashMap<>();
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return R.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error("更新图像失败！");
        }
    }

    @ResponseBody
    @PostMapping(value = "/shoplist", produces = "application/json;charset=UTF-8")
    R getShopList() {
        Map<String, Object> result = new HashMap<>();
        List<Shop> list3 = shopService.selectAllList();
        result.put("shops", list3);
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error();
        }
    }

    @ResponseBody
    @PostMapping(value = "/realationList", produces = "application/json;charset=UTF-8")
    R getUserShopList(@RequestParam("userId") Integer userId) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = new ArrayList<>();
        List<UserShopRelation> relationList = new ArrayList<>();
        UserDO userDO = getUser();
        UserDO user = userService.getById(userId);
        Map<String, Object> map = new HashMap<>();
        if (user.getUserType() == 2) {//集团管理员
            relationList = userShopRelationService.selectListByColumn("jituan_user_id", userId);
        } else if (user.getUserType() == 3 || user.getUserType() == 12) {//分区管理员、检测
            relationList = userShopRelationService.selectListByColumn("sys_user_id", userId);
        }

        if (relationList != null) {
            relationList.forEach(relation -> {
                list.add(relation.getShopId() + "");
            });
        }

        List<Map<String, Object>> listAllShop = new ArrayList<>();
        List<Shop> listShop = new ArrayList<>();
        if (userDO.getUserType() == 0 || userDO.getUserType() == 1) {
            listShop = shopService.selectAllList();
        } else if (userDO.getUserType() == 2) {//集团管理员
            map.put("jituan_user_id", user.getJituanId());
            listShop = shopService.getPageByUserId(map);
        } else if (userDO.getUserType() == 3) {//分区管理员
            map.put("sys_user_id", userId);
            listShop = shopService.getPageByUserId(map);
        }  else if (userDO.getUserType() == 12) {//监测设备企业
            map.put("shop_type", 4);
            listShop = shopService.getPageByUserId(map);
        }

        if (listShop != null) {
            listShop.forEach(shop -> {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("value", shop.getId());
                map1.put("title", shop.getShopName());
                listAllShop.add(map1);
            });
        }

        result.put("relation_list", list);
        result.put("shops", listAllShop);
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error();
        }
    }

    @ResponseBody
    @PostMapping(value = "/bandShop", produces = "application/json;charset=UTF-8")
    R bandShop(@RequestParam("userId") Integer userId, @RequestParam("shops") String shops,
               @RequestParam("op_type") Integer op_type) {
        UserDO userDO = userService.get(userId);
        if (userDO != null) {
            JSONArray jsonArray = JSONArray.fromObject(shops);
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Integer shopId = jsonObject.getInt("value");
                    if (op_type == 1) {//删除
                        QueryWrapper<UserShopRelation> qw = new QueryWrapper<>();
                        qw.eq("sys_user_id", userId);
                        qw.eq("shop_id", shopId);
                        UserShopRelation relation = userShopRelationService.getOne(qw);
                        if (relation != null) {
                            userShopRelationService.removeById(relation);
                        }
                    } else {//添加
                        QueryWrapper<UserShopRelation> qw = new QueryWrapper<>();
                        qw.eq("sys_user_id", userId);
                        qw.eq("shop_id", shopId);
                        UserShopRelation relation = userShopRelationService.getOne(qw);
                        if (relation == null) {
                            relation = new UserShopRelation();
                            relation.setJituanUserId(userDO.getGroupId());
                            relation.setSysUserId(userId);
                            relation.setShopId(shopId);
                            userShopRelationService.save(relation);
                        }
                    }
                }
            }
            return R.ok();
        } else {
            return R.error();
        }
    }


    @ResponseBody
    @PostMapping(value = "/selectUserByUserType", produces = "application/json;charset=UTF-8")
    R getShopList(@RequestParam("userId") Integer userId, @RequestParam("userType") Integer userType) {
        Map<String, Object> result = new HashMap<>();
        UserDO user = userService.getById(userId);
        result.put("code", "00");
        int sys_user_id = 0;
        if (user != null) {
            QueryWrapper<UserDO> qw = new QueryWrapper<>();
            if (user.getUserType() == 2 || user.getUserType() == 3) {
                if (user.getUserType() == 2) {
                    qw.eq("group_id", user.getGroupId());
                }
                if (user.getUserType() == 3) {
                    qw.eq("fenchang_id", userId);
                }
                qw.eq("user_type", userType);
                List<UserDO> users = userService.list(qw);
                if (userType == 3) {
                    if (users != null && users.size() > 0) {
                        sys_user_id = users.get(0).getUserId();
                    }
                }
                result.put("users", users);
                result.put("users_count", users.size());
            }

            if (userType == 4) {
                sys_user_id = userId;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("sys_user_id", sys_user_id);
            List<Shop> shops = shopService.getPageByUserId(map);
            result.put("shops_count", shops.size());
            result.put("shops", shops);
            if (result != null && result.size() > 0) {
                return R.ok(result);
            } else {
                return R.error();
            }
        }
        return R.error();
    }


    @ResponseBody
    @PostMapping(value = "/selectUserByPianquId", produces = "application/json;charset=UTF-8")
    R selectUserByPianquId(@RequestParam("userType") Integer userType, @RequestParam("pianquId") Integer pianquId) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", "00");
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        qw.eq("user_type", userType);
        qw.eq("pianqu_id", pianquId);
        List<UserDO> users = userService.list(qw);
        result.put("users", users);
        result.put("users_count", users.size());
        if (users != null && users.size() > 0) {
            return R.ok(result);
        } else {
            return R.error();
        }
    }


    @RequiresPermissions("sys:user:fenchang:synchronize")
    @ResponseBody
    @PostMapping(value = "/getUserMpList", produces = "application/json;charset=UTF-8")
    R getUserMpList() {
        String accessToken = WxMessage.getACCESSTOKEN(appidMp, secretMp);
        System.out.println("accessToken:" + accessToken);
        JSONObject jsonObject = WxMessage.getUserMp(accessToken, "");
        int userCount = 0;
        if (jsonObject != null) {
            System.out.println(jsonObject.toString());
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    String openid = jsonArray.getString(i);
                    JSONObject userInfo = WxMessage.getUserMpInfo(accessToken, openid);
                    if (userInfo != null && userInfo.size() > 0) {
                        String openId = userInfo.getString("openid");
                        String unionId = userInfo.getString("unionid");
                        String nickname = userInfo.getString("nickname");
                        String faceurl = userInfo.getString("headimgurl");
                        UserMp userMp = userMpService.selectByUniqueColumn("unionid", unionId);
                        if (userMp == null) {
                            userMp = new UserMp();
                            userMp.setOpenid(openId);
                            userMp.setUnionid(unionId);
                            userMp.setFaceUrl(faceurl);
                            userMp.setNickName(nickname);
                            userMp.setCreateTime(new Date());
                            boolean bl = userMpService.save(userMp);
                            if (bl) {
                                userCount++;
                            }
                        }
                    }
                }
            }
        }
        return R.ok();
    }

//    @RequiresPermissions(value = {"sys:user:checkDanger:user","sys:user:checkDanger:userShop"})
    @GetMapping("/checkDanger")
    String checkDanger(Model model) {
        UserDO user = getUser();
        QueryWrapper<Towns> qwTown = new QueryWrapper<>();
        qwTown.eq("parent_id", 0);
        qwTown.eq("district_id", 1319);
        List<Towns> townsList = townsService.list(qwTown);
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        wrapper.ne("shop_type", 3);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }
        if (user.getGroupId() != null && user.getGroupId() > 0) {
            wrapper.eq("group_id", user.getGroupId());
        }
        List<Shop> shopList = shopService.list(wrapper);
        model.addAttribute("townsList", townsList);
        model.addAttribute("shopList", shopList);
        model.addAttribute("user", user);
        model.addAttribute("userType", 10);
        return prefix + "/check_danger_user";
    }

//    @RequiresPermissions(value = {"sys:user:checkDanger:user","sys:user:checkDanger:userShop"})
    @GetMapping("/checkDanger/{shopId}")
    String checkDanger1(Model model,@PathVariable("shopId") Integer shopId) {
        UserDO user = getUser();
        Shop shop = shopService.findById(shopId);
        if(shop!= null){
            model.addAttribute("townId", shop.getTownId());

            List<Department> deptList = departmentService.selectListByColumn("company_id", shopId);
            model.addAttribute("deptList", deptList);
        }
        model.addAttribute("shopId", shopId);
        model.addAttribute("user", user);
        model.addAttribute("userType", 10);
        return prefix + "/check_danger_user_company";
    }

    /**
     * 隐患举报人员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/check_danager_list")
    @ResponseBody
    DataTableLayUI<UserDO> checkDanagerList(DataTableLayUI<UserDO> condition) {
        Map<String, Object> map = condition.getSearchParams();
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        String townId = map.containsKey("search_eq_townId") ? map.get("search_eq_townId").toString() : null;
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString() : null;
        UserDO user = getUser();
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
//        qw.eq("user_type", 10);

        if (StrUtil.isNotEmpty(keyword)) {
//            qw.like("name", keyword);
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        if (user.getShopId() != null && user.getShopId() > 0) {
            if (shopId != null){
                qw.eq("shop_id", shopId);
            }else {
                qw.eq("shop_id", user.getShopId());
            }
        } else {
            if (StrUtil.isNotEmpty(shopId)) {
                qw.eq("shop_id", shopId);
            }
        }
        if (user.getTownId() != null && user.getTownId() > 0) {
            qw.eq("town_id", user.getTownId());
        } else {
            if (StrUtil.isNotEmpty(townId)) {
                qw.eq("town_id", townId);
            }
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        for (int i = 0; i < list.size(); i++) {
            UserDO userDO = list.get(i);
            if (userDO.getRoleId() == null) {
                continue;
            }
            RoleDO roleDO = roleService.findById(userDO.getRoleId());
            if (roleDO == null) {
                continue;
            }
            userDO.setRoleName(roleDO.getRoleName());

            if (userDO.getDeptId() != null) {
                Department department = departmentService.findById(userDO.getDeptId());
                if (department != null) {
                    userDO.setDeptName(department.getName());
                }
            }
            userDO.setIsGuanZhuMp("未关注");
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", userDO.getUserId());
            if (users != null) {
                String name = "";
                String guanzhu = "";
                for (WxUser wxUser : users) {
                    String nick_name = "";
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                        nick_name = EmojiParser.parseToUnicode(wxUser.getNickName());
                    }
                    UserMp userMp = userMpService.selectByUniqueColumn("unionid", wxUser.getUnionId());
                    if (userMp != null) {
                        guanzhu += nick_name + " : 已关注、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                } else {
                    name = "未绑定微信用户";
                }
                if (!guanzhu.equals("")) {
                    guanzhu = guanzhu.substring(0, guanzhu.length() - 1);
                } else {
                    guanzhu = "未关注";
                }
                userDO.setWxNickName(name);
                userDO.setIsGuanZhuMp(guanzhu);
            } else {
                userDO.setWxNickName("未绑定微信用户");
            }

        }
        return dt;
    }

    @RequiresPermissions("sys:user:storeuser:user")
    @GetMapping("/storeuser")
    String storeuser(Model model) {
        model.addAttribute("userType", 11);
        return prefix + "/store_user";
    }

    /**
     * 仓库管理员列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/store_list")
    @ResponseBody
    DataTableLayUI<UserDO> store_list(DataTableLayUI<UserDO> condition) {
        UserDO user = getUser();
        Map<String, Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString() : null;
        String userType = map.containsKey("search_eq_userType") ? map.get("search_eq_userType").toString() : null;
        String keyword = map.containsKey("search_like_name") ? map.get("search_like_name").toString() : null;
        Integer shop_id = 0;
        QueryWrapper<UserDO> qw = new QueryWrapper<>();
        if (userType != null) {
            qw.eq("user_type", Integer.parseInt(userType));
        } else {
            qw.eq("user_type", 11);//默认5 巡检用户
        }
        if (StrUtil.isNotEmpty(shopId)) {
            shop_id = Integer.parseInt(shopId);
            qw.eq("shop_id", shop_id);
        }
        if (user.getUserType() == 2) {
            qw.eq("group_id", user.getGroupId());
        } else if (user.getUserType() == 3) {
            qw.eq("pianqu_user_id", user.getUserId());
        } else if (user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6) {
            qw.eq("shop_id", user.getShopId());
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.and(wrapper ->
                    wrapper.like("name", keyword).or().like("mobile", keyword).or().like("username", keyword)
            );
        }
        qw.orderByDesc("user_id");
        condition.setQw(qw);
        DataTableLayUI<UserDO> dt = userService.pageSearchLayUI(condition);
        List<UserDO> list = dt.getData();
        for (UserDO user1 : list) {
            Shop shop = shopService.findById(user1.getShopId());
            if (shop != null) {
                user1.setShopName(shop.getShopName());
            }

            user1.setIsGuanZhuMp("未关注");
            List<WxUser> users = wxUserService.selectListByColumn("sys_user_id", user1.getUserId());
            if (users != null) {
                String name = "";
                String guanzhu = "";
                for (WxUser wxUser : users) {
                    String nick_name = "";
                    if (StrUtil.isNotEmpty(wxUser.getNickName())) {
                        name += EmojiParser.parseToUnicode(wxUser.getNickName()) + "、";
                        nick_name = EmojiParser.parseToUnicode(wxUser.getNickName());
                    }
                    UserMp userMp = userMpService.selectByUniqueColumn("unionid", wxUser.getUnionId());
                    if (userMp != null) {
                        guanzhu += nick_name + " : 已关注、";
                    }
                }
                if (!name.equals("")) {
                    name = name.substring(0, name.length() - 1);
                } else {
                    name = "未绑定微信用户";
                }
                if (!guanzhu.equals("")) {
                    guanzhu = guanzhu.substring(0, guanzhu.length() - 1);
                } else {
                    guanzhu = "未关注";
                }
                user1.setWxNickName(name);
                user1.setIsGuanZhuMp(guanzhu);
            } else {
                user1.setWxNickName("未绑定微信用户");
            }
        }
        return dt;
    }
}
